import requests
from bs4 import BeautifulSoup
import json
import time

class dedecms():
    def __init__(self,dedeurl,session,username,password,code,charset=1):
        self.dedeurl = dedeurl
        self.charset = 'utf-8' if charset==1 else 'gb2312'
        self.headers = {
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36',

        }
        self.session = session
        self.username = username
        self.password = password
        self.code = code

    def set_cookie(self,fcookie):
        """
        设置cookie
        :param fcookie:
        """
        cookies = requests.utils.cookiejar_from_dict(fcookie, cookiejar=None, overwrite=True)
        self.session.cookies = cookies;

    def check(self):
        """
        检查cookie是否有效
        :return: bool
        """
        checkurl = self.dedeurl+'/index_body.php';
        res = self.session.get(checkurl,headers=self.headers,allow_redirects=False)
        if res.status_code==200:
            return True
        else:
            return False


    def login(self,code):
        """
        登录网站
        :param username:
        :param password:
        :param code:
        :return: json
        """
        login_url = self.dedeurl+'/login.php'
        data = {
            'gotopage': '',
            'dopost': 'login',
            'adminstyle': 'newdedecms',
            'userid': self.username,
            'pwd': self.password,
            'validate': code,
            'sm1': ''
        }
        con = self.session.post(login_url,headers=self.headers,data=data)
        if con.status_code == 404:
            return False,404
        if con.status_code == 200:
            content = con.content.decode(self.charset)
            if content.find('你的用户名不存在')>0:
                return False,'你的用户名不存在'
            if content.find('验证码不正确')>0:
                return False,'验证码不正确'
            if content.find('你的密码错误')>0:
                return False,'你的密码错误'
            if content.find('成功登录')>0:
                con1 = self.session.get(self.dedeurl+'/index.php',headers=self.headers)
                cookies = requests.utils.dict_from_cookiejar(self.session.cookies)
                return True,json.dumps(cookies)
            return False,'error'

    def getTypelist(self):
        """
        获取后台分类
        :return: Array
        """
        try:
            listurl = self.dedeurl+'/makehtml_list.php'
            con = self.session.get(listurl,headers=self.headers).content.decode(self.charset)
            soup = BeautifulSoup(con,'lxml')
            sel = soup.find_all('select',attrs={"name":"typeid"})[0].find_all('option')
            typearr = []
            for i in sel:
                v = i['value']
                if v=="0":
                    continue
                name = i.string
                typearr.append({'id':v,'name':name})
            return typearr
        except Exception as e:
            print(e)
            return None
    
    def getArtlist(self):
        """
        获取文章列表
        :return:
        """
        listurl = self.dedeurl+'/content_list.php'
        con = self.session.get(listurl,headers=self.headers)
        if con.status_code == 200:
            soup = BeautifulSoup(con.content.decode(self.charset),'lxml')
            sel = soup.select('body > form tr')[2:]
            data = []
            for i in sel:
                str1 = i.find_all('td')
                if len(str1)>4:
                    if str1[2].find('u'):
                        data.append({
                            'id' : str1[0].string.strip(),
                            'title' : str1[2].find('u').string,
                            'updatetime' : str1[3].string,
                            'catname' : str1[4].string
                            })
            return data
        return False

    def add(self,senddata):
        """
        发布文章
        :param senddata:
        :return:
        """
        if not senddata:
            print('数据为空！')
            exit()
        if self.charset == 'gb2312':
            senddata['title'] = senddata['title'].encode('gb2312',errors="ignore")
            senddata['body'] = senddata['body'].encode('gb2312',errors="ignore")
        self.addurl = self.dedeurl+"/article_add.php"
        pubdate = int(time.time())
        data = {
            'channelid': '1',
            'dopost': 'save',
            'title': senddata['title'],
            'shorttitle': '',
            'flags[]': '',
            'redirecturl': '',
            'tags': '',
            'weight': '4',
            'picname': '',
            'source': '',
            'writer': '',
            'typeid': senddata['typeid'],
            'typeid2': '',
            'keywords': '',
            'autokey': 1,
            'description': '',
            'dede_addonfields': '',
            'remote': 1,
            'autolitpic': 1,
            'needwatermark': 1,
            'sptype': 'hand',
            'spsize': 5,
            'body': senddata['body'],
            'voteid': '',
            'notpost': 0,
            'click': 94,
            'sortup': 0,
            'color': '',
            'arcrank': 0,
            'money': 0,
            'pubdate': pubdate,
            'ishtml': 1,
            'filename': '',
            'templet': '',
            'imageField.x': 27,
            'imageField.y': 12
            }
        con = self.session.post(self.addurl,headers=self.headers,data=data).content.decode(self.charset)
        if con.find('成功发布文章')>0:
            return True , con
        else:
            print("发布失败")
            return False , ''

    def makeChild(self,id):
        """
        同步生成子网站文章页面
        :param id:
        :return:
        """
        geturl = "{}/archives_do.php?aid={}&dopost=viewArchives".format(self.dedeurl,id)
        res = self.session.get(geturl,headers=self.headers)
        if res.status_code == 200:
            content = res.content.decode(self.charset)
            if content.find('对不起') > 0:
                return False
            else:
                return True

    def getMakeHTMLConfig(self):
        """
        获取生成首页相关信息
        :return:
        """
        geturl = "{}/makehtml_homepage.php".format(self.dedeurl)
        res = self.session.get(geturl,headers=self.headers)
        if res.status_code == 200 :
            try:
                con = res.content.decode(self.charset)
                soup = BeautifulSoup(con,'lxml')
                templet = soup.find_all(id="templet")[0]['value']
                position = soup.find_all(id="position")[0]['value']
                return templet,position
            except Exception as e:
                return False,False

    def makeHTML(self):
        """
        生成首页
        :return:
        """
        templet, position = self.getMakeHTMLConfig()
        geturl = "{}/makehtml_homepage.php".format(self.dedeurl)
        postdata = {
            'dopost': 'make',
            'templet': templet,
            'position':position,
            'saveset': '1',
            'showmod': '1',
            'Submit': '更新主页HTML',
        }
        res = self.session.post(geturl,headers = self.headers,data=postdata)
        if res.status_code == 200:
            con = res.content.decode(self.charset)
            if con.find("成功更新") >= 0:
                return True
        return False

    def makeRSS(self):
        """
        更新网站RSS地图
        :return:
        """
        geturl = "{}/makehtml_map.php?dopost=rss".format(self.dedeurl)
        try:
            res = self.session.get(geturl,headers=self.headers)
            con = res.content.decode("utf-8")
            if con.find("成功更新") > 0 :
                return True
        except Exception as e:
            print(e)
            return False


    def makeCateHtml(self,id):
        """
        批量更新列表
        :return:
        """
        try:
            geturl = "{}/makehtml_list_action.php?gotype=&uppage=0&maxpagesize=50&typeid=0&pageno={}&isremote=0&serviterm=".format(self.dedeurl,id)
            res = self.session.get(geturl,headers = self.headers)
            if res.status_code == 200:
                con = res.content.decode("utf-8")
                if con.find("完成所有列表更新")>0:
                    return 1
                else:
                    return 0
            else:
                return -2
        except Exception as e:
            print(e)
            return -1
